package com.dhcc.DRGsHosp.application.impl;

import com.dhcc.DRGsHosp.application.ClinicGroupApplication;
import com.dhcc.DRGsHosp.core.domain.ClinicGroup;
import com.dhcc.DRGsHosp.core.domain.MrIpInfo;
import com.dhcc.DRGsHosp.core.domain.MrOperation;
import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.dayatang.querychannel.QueryChannelService;
import org.openkoala.koalacommons.resourceloader.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Named;
import java.util.*;

@Named
@Transactional
public class ClinicGroupApplicationImpl implements ClinicGroupApplication {
	private static final Logger LOGGER = LoggerFactory.getLogger(ClinicGroupApplicationImpl.class);
	
	@Autowired  
    private JdbcTemplateObj jdbcTemplateObj; 
	@Autowired
	private NamedParameterJdbcTemplate jdbcTempSeverice;
	
	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
    
    private EntityRepository getRepository() {
		EntityRepository repository = null;
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository");
		}
		return repository;
	}
	
	@Override
	public String findClinicGroupsByDepCode(String depCode) {
		String sql="select cg.group_name from drgs.t_clinicgroup cg where cg.pardep_code = '"+depCode+"'";
//		String jpql="select DISTINCT mr.p00601000 from drgs.Mr_IpInfo mr where mr.p00260001 = '"+depCode+"'";
		List<String> clinicNames = jdbcTemplateObj.queryForList(sql, String.class);

		String names = "";
		for (String clnicName : clinicNames) {
			if(StringUtils.hasLength(clnicName)){
				names += clnicName +",";
			}
		}
		if(StringUtils.hasLength(names)){
			names = names.substring(0, names.lastIndexOf(","));
		}
		return names;
	}

	public ClinicGroup getClinicGroup(Long id) {
		return ClinicGroup.get(ClinicGroup.class, id);
	}
	
	@Override
	public void saveClinicGroup(Map<String,Object> json) {
		// 判断map集合里是否有空值
			Iterator<Map.Entry<String, Object>>  entryIt = json.entrySet().iterator() ;
			while (entryIt.hasNext()) {
				Map.Entry<String, Object> entry = entryIt.next();
				if(entry.getValue() == null || "".equals(entry.getValue().toString())) {
					if("id".equals(entry.getKey())) continue ;
					json.put(entry.getKey(), "") ;
				}
			}
			StringBuffer sql = new StringBuffer() ;
			// 增加 
			if( null == json.get("id")) {
				json.put("id", UUID.randomUUID().toString().replaceAll("-", "")) ;
				sql.append(" insert into drgs.t_clinicgroup cc  \n") ;
				sql.append(" (cc.id,cc.group_order,cc.pardep_code,cc.parward_code,cc.group_code,cc.group_name,cc.group_type,cc.pardepgroup_code) \n") ;
				sql.append(" values(:id,:groupOrder,:parDepCode,:parWardCode,:groupCode,:groupName,:groupType,:parDepGroupCode) \n") ;
			} else { // 更新
				sql.append(" update drgs.t_clinicgroup cc \n") ;
				sql.append(" set cc.group_order=:groupOrder, cc.pardep_code = :parDepCode,cc.parward_code = :parWardCode , cc.group_code = :groupCode ,cc.group_name = :groupName ,cc.group_type = :groupType,cc.pardepgroup_code = :parDepGroupCode \n") ;
				sql.append(" where cc.id = :id \n") ;
			}
			getRepository().createSqlQuery(sql.toString()).setParameters(json).executeUpdate();
	}
	
	public void removeClinicGroup(ClinicGroup clinicGroup) {
		StringBuffer sql = new StringBuffer(" delete from drgs.t_clinicgroup cc where 1=1 \n ") ; 
		String sqls = sql.toString() ;
		if(clinicGroup.getId() != null) {
			sqls = sqls.replaceAll(" 1=1 "," cc.id = :id and 1=1 ") ;
		}
		if(StringUtils.hasLength(clinicGroup.getGroupCode())) {
			sqls = sqls.replaceAll(" 1=1 "," cc.group_code = :groupCode and 1=1 ") ;
		}
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(clinicGroup);
		jdbcTempSeverice.update(sqls, paramSource) ;
	}
	
	public List<ClinicGroup> findAllClinicGroup() {
		return ClinicGroup.findAll(ClinicGroup.class);
	}

	@Override
	public List<ClinicGroup> findAllClinicGroup(ClinicGroup entity) {
		String depCode = entity.getParDepCode();
		StringBuilder jpql = new StringBuilder("select new ClinicGroup(id,groupName,groupCode,groupType,parDepCode,parWardCode,groupActive,groupOrder,parDepGroupCode) from ClinicGroup clinicGroup");
		if(StringUtils.hasLength(depCode)) {
			jpql.append(" where clinicGroup.parDepCode='"+depCode+"'");
		}
		List<ClinicGroup> clinicGroups = getQueryChannelService()
			   .createJpqlQuery(jpql.toString())
			   .list();
		return clinicGroups;
	}

	@Override
	public Boolean isGroupCodeExist(String groupCode) {
		String sql = "select count( clinicGroup.group_code ) from drgs.t_clinicGroup clinicGroup where clinicGroup.group_code='"+groupCode+"'";
	    int count = jdbcTemplateObj.queryForObject(sql,Integer.class) ;
		if( count > 0 ){
			return true ;
		}
		return false ;
	}

	@Override
	public List<Map<String,Object>> excuteQuery(String sql, Map<String, Object> params) {
		List<Map<String,Object>> listMap = jdbcTempSeverice.queryForList(sql, params) ;
		return listMap;
	}

	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.application.ClinicGroupApplication#creatClinicGroup(com.dhcc.DRGsHosp.core.domain.ClinicGroup)  
	 */
	@Override
	public void creatClinicGroup(ClinicGroup clinicGroup) {
		clinicGroup.save();
	}

	@Override
	public List<String> findAllDoctorCodeInIpinfo() {
		StringBuffer strb = new StringBuffer() ;
		strb.append(" select ipinfo.P00600101 doccode from drgs.mr_ipinfo ipinfo \n") ;
		strb.append(" union \n") ;
		strb.append(" select ipinfo.P00600201 doccode from drgs.mr_ipinfo ipinfo \n") ;
		strb.append(" union \n") ;
		strb.append(" select ipinfo.P00600301 doccode from drgs.mr_ipinfo ipinfo \n") ;
		strb.append(" union \n") ;
		strb.append(" select ipinfo.P00600401 doccode from drgs.mr_ipinfo ipinfo \n") ;
		strb.append(" union \n") ;
		strb.append(" select ipinfo.P00601001 doccode from drgs.mr_ipinfo ipinfo \n") ;
		return jdbcTemplateObj.queryForList(strb.toString(), String.class) ;
	}

	@Override
	public void updateDoctorCodeInIpinfo(String oldCode, String newCode) {
		String[] sql = new String[8] ; 
		sql[0] = " update drgs.mr_ipinfo set P00600101 = '"+newCode+"' where P00600101 = '"+oldCode+"' \n " ;
		sql[1] = " update drgs.mr_ipinfo set P00600201 = '"+newCode+"' where P00600201 = '"+oldCode+"' \n " ;
		sql[2] = " update drgs.mr_ipinfo set P00600301 = '"+newCode+"' where P00600301 = '"+oldCode+"' \n " ;
		sql[3] = " update drgs.mr_ipinfo set P00600401 = '"+newCode+"' where P00600401 = '"+oldCode+"' \n " ;
		sql[4] = " update drgs.mr_ipinfo set P00601001 = '"+newCode+"' where P00601001 = '"+oldCode+"' \n " ;
		sql[5] = " update drgs.MR_OPERATION set PO0401 = '"+newCode+"' where PO0401 = '"+oldCode+"' \n " ;
		sql[6] = " update drgs.MR_OPERATION set PO0501 = '"+newCode+"' where PO0501 = '"+oldCode+"' \n " ;
		sql[7] = " update drgs.MR_OPERATION set PO0601 = '"+newCode+"' where PO0601 = '"+oldCode+"' \n " ;
		try {
			jdbcTemplateObj.batchUpdate(sql) ;
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
	}
	
	@Override
	public void updateDoctorCodeById(Object obj) {
		StringBuffer strb = new StringBuffer() ;
		if(obj instanceof MrIpInfo) {
			strb.append(" update drgs.mr_ipinfo ipinfo set \n ") ;
			MrIpInfo ipinfo = (MrIpInfo)obj ;
			if(StringUtils.hasLength(ipinfo.getP00600101())) {
				strb.append(" ipinfo.p00600101 = :p00600101 , \n ") ;
				strb.append(" ipinfo.p00600100 = :p00600100 , \n ") ;
			}
			if(StringUtils.hasLength(ipinfo.getP00600201())) {
				strb.append(" ipinfo.p00600201 = :p00600201 , \n ") ;
				strb.append(" ipinfo.p00600200 = :p00600200 , \n ") ;
			}
			if(StringUtils.hasLength(ipinfo.getP00600301())) {
				strb.append(" ipinfo.p00600301 = :p00600301 , \n ") ;
				strb.append(" ipinfo.p00600300 = :p00600300 , \n ") ;
			}
			if(StringUtils.hasLength(ipinfo.getP00600401())) {
				strb.append(" ipinfo.p00600401 = :p00600401 , \n ") ;
				strb.append(" ipinfo.p00600400 = :p00600400 , \n ") ;
			}
			if(StringUtils.hasLength(ipinfo.getP00601001())) {
				strb.append(" ipinfo.p00601001 = :p00601001 , \n ") ;
				strb.append(" ipinfo.p00601000 = :p00601000 , \n ") ;
			}
			String sql = strb.toString() ;//subSequence(beginIndex, endIndex)
			strb = new StringBuffer(sql.substring(0, sql.lastIndexOf(","))) ;
			strb.append(" where  ipinfo.pmainindex = :pmainIndex \n ") ;
		} else if(obj instanceof MrOperation) {
			strb.append(" update drgs.mr_operation ope set \n ") ;
			MrOperation ope = (MrOperation)obj ;
			if(StringUtils.hasLength(ope.getPo0401())) {
				strb.append(" ope.po0401 = :po0401, \n ") ;
				strb.append(" ope.po0400 = :po0400, \n ") ;
			}
			if(StringUtils.hasLength(ope.getPo0501())) {
				strb.append(" ope.po0501 = :po0501, \n ") ;
				strb.append(" ope.po0500 = :po0500, \n ") ;
			}
			if(StringUtils.hasLength(ope.getPo0601())) {
				strb.append(" ope.po0601 = :po0601, \n ") ;
				strb.append(" ope.po0600 = :po0600, \n ") ;
			}
			String sql = strb.toString() ;//subSequence(beginIndex, endIndex)
			strb = new StringBuffer(sql.substring(0, sql.lastIndexOf(","))) ;
			strb.append(" where ope.id = :id \n ") ;
		}
		
		try {
			SqlParameterSource paramSource = new BeanPropertySqlParameterSource(obj);
			jdbcTempSeverice.update(strb.toString(), paramSource) ;
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
	}

	@Override
	public void updateDoctorCodeInClinicGroup(String oldCode, String newCode) {
		String sql = "update drgs.t_clinicgroup set group_code = '"+newCode+"' where group_code = '"+oldCode+"'" ;
		jdbcTemplateObj.update(sql) ;
	}

	@Override
	public List<Map<String, Object>> queryDoctorByMultiDep(String outDepCode, String type, String doctorName) {
		String sql = " select t.id,t.group_code,t.pardep_code from drgs.T_CLINICGROUP t where t.pardep_code like '%"+outDepCode+"%' and t.group_type = '"+type+"' and t.group_name = '"+doctorName+"'  " ;
		return jdbcTemplateObj.queryForList(sql) ;
	}


	@Override
	public List<Map<String,Object>> findCaseCntDocCodeIsNull(String sql, Map<String, Object> params) {
		return jdbcTempSeverice.queryForList(sql, params) ;
	}

	@Override
	public int[] updateIpinfoAndClinicGroup(String[] sql) {
		int[] value = null ;
		try {
			value = jdbcTemplateObj.batchUpdate(sql) ;
		} catch (DataAccessException e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
			return value ;
		}
		return value ;
	}

	@Override
	public Integer excuteUpdate(String sql, Map<String, Object> params) {
		Integer rowCount = null ;
		try {
			rowCount = jdbcTempSeverice.update(sql, params) ;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
			return rowCount ;
		}
		return rowCount ;
	}
	
	@Override
	public int updateClinicGroupByDocCode(ClinicGroup clinicGroup,boolean flag) {
		StringBuffer strb = new StringBuffer(" update drgs.t_clinicgroup cg  set ") ;
		// flag == true,更新全部字段  
		if(flag) {
			strb.append(" cg.group_name =:groupName,cg.GROUP_TYPE =:groupType,cg.PARDEP_CODE =:parDepCode,cg.PARWARD_CODE =:parWardCode, cg.GROUP_ACTIVE =:groupActive,cg.GROUP_ORDER =:groupOrder,cg.PARDEPGROUP_CODE =:parDepGroupCode ,  ") ;
		} else {  //flag == false 不全部跟新，根据字段情况拼接 
			if(StringUtils.hasLength(clinicGroup.getGroupName()) && flag == false) {
				strb.append(" cg.group_name =:groupName, ") ;
			}
			if(StringUtils.hasLength(clinicGroup.getGroupType())) {
				strb.append(" cg.GROUP_TYPE =:groupType, ") ;
			}
			if(StringUtils.hasLength(clinicGroup.getParDepCode())) {
				strb.append(" cg.PARDEP_CODE =:parDepCode, ") ;
			}
			if(StringUtils.hasLength(clinicGroup.getParWardCode())) {
				strb.append(" cg.PARWARD_CODE =:parWardCode, ") ;
			}
			if(clinicGroup.getGroupActive() != null ) {
				strb.append(" cg.GROUP_ACTIVE =:groupActive, ") ;
			}
			if(StringUtils.hasLength(clinicGroup.getGroupOrder())) {
				strb.append(" cg.GROUP_ORDER =:groupOrder, ") ;
			}
			if(StringUtils.hasLength(clinicGroup.getParDepGroupCode())) {
				strb.append(" cg.PARDEPGROUP_CODE =:parDepGroupCode , ") ;
			}
		}
		
		String sql = strb.toString() ;
		if(sql.lastIndexOf(",")>0) {
			strb = new StringBuffer(sql.substring(0, sql.lastIndexOf(","))) ;
			strb.append(" \n where cg.group_code = :groupCode ") ;
			SqlParameterSource paramSource = new BeanPropertySqlParameterSource(clinicGroup);
			return jdbcTempSeverice.update(strb.toString(), paramSource ) ;
		} else {
			return 0 ;
		}
	}

	@Override
	public Boolean isGroupOrderExist(String groupOrder, String groupCode) {
		String sql1 = "select count(1) from drgs.t_clinicgroup cg where cg.group_order = :groupOrder" ;
		String sql2 = "select count(1) from drgs.t_clinicgroup cg where cg.group_order = :groupOrder and cg.group_code <> :groupCode" ;
		String sql = null ;
		Map<String,Object> params = new HashMap<>() ;
		// 增加时判断
		if( groupCode == null  ) {
			sql = sql1 ;
		} else { // 更新时判断
			params.put("groupCode", groupCode) ;
			sql = sql2 ;
		}
		params.put("groupOrder", groupOrder != null ? groupOrder : "") ;
		Integer count = jdbcTempSeverice.queryForObject(sql, params, Integer.class) ;
		if( count == 0 ) {
			return false ;
		} 
		return true;
	}
	
	/**
	 *  
	 *  getMaxOrder  
	 *  @Description：查找最大医师序号
	 *  @Author fulianxia
	 *  @param  
	 *  @Date:2018年3月26日
	 */
	@Override
	public int getMaxOrder() {
		int groupOrder = 0;
		String sql = "select max(cg.group_order) from drgs.t_clinicgroup cg " ;
		String result = (String)getQueryChannelService().createSqlQuery(sql).singleResult();
		if(result != null){
			groupOrder = Integer.parseInt(result);
		}else{
			groupOrder = 0;
		}
		return groupOrder;
	}
}
